package com.zrq.jwtdemo.core.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.zrq.jwtdemo.core.prop.JwtProp;
import io.jsonwebtoken.*;
import lombok.AllArgsConstructor;
import org.apache.catalina.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: zrq
 * @CreateDate: 2020/12/10
 * @Version: 类说明： jwt工具类
 */
@Configuration
@AllArgsConstructor
@Component
public class JwtUtils {

    private final JwtProp jwtProp;

    /**
     * 成生token
     * @return
     */
    public String getToken(Map<String,Object> map) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, jwtProp.getExpiration());
        String token = Jwts.builder()
                .setClaims(map)
                .setExpiration(instance.getTime())
                .signWith(SignatureAlgorithm.HS256,jwtProp.getKey()).compact();

        return token;
    }

    /**
     * 验证token
     * @param token
     */
    public Object verify(String token) {
//        JWT.require(Algorithm.HMAC256(jwtProp.getKey())).build().verify(token);
        Claims body = Jwts.parser()
                .setSigningKey(jwtProp.getKey())
                .parseClaimsJws(token).getBody();
        Object userId = body.get("userId");
        return userId;
    }

    /**
     * 根据token获取userId
     * @param token
     */
    public Integer getUserId(String token) {
        Claims body = Jwts.parser()
                .setSigningKey(jwtProp.getKey())
                .parseClaimsJws(token).getBody();
        Integer userId = (Integer) body.get("userId");
        return userId;
    }

}
